package com.hwd.srb.sms.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hwd.srb.base.dto.SmsDTO;
import com.hwd.srb.rabbitmq.constant.MQConst;
import com.hwd.srb.sms.service.SmsService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 黄伟东/Victor
 * @date 2022/3/28 12:00
 * @Description rabbitmq消息消费者
 */
@Component
@Slf4j
public class SmsConsumer {

    @Resource
    private SmsService smsService;

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MQConst.EXCHANGE_TOPIC_SMS),
            key = {MQConst.ROUTING_SMS_ITEM},
            value = @Queue(value = MQConst.QUEUE_SMS_ITEM ,durable = "true")
    ))
    public void send(Channel channel, Message message, SmsDTO smsDTO) throws IOException {

        log.info("SmsReceiver 消息监听");

        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            String str = new String(message.getBody());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//            int a = 10 /0;
//            Map map1 = JSON.parseObject(str, Map.class);

            smsService.notifyMessage(smsDTO.getMobile(), smsDTO.getMessage());
            channel.basicAck(deliveryTag, true);
        } catch (IOException e) {
            e.printStackTrace();
            channel.basicNack(deliveryTag, true, true);
        }

    }
}
